package com.umakr.ax;

import com.umakr.ax.core.aspect.ChooseDataSource;
import com.google.common.collect.Maps;
import com.umakr.ax.core.config.DruidDataSource;
import com.umakr.ax.core.config.DruidDataSourceProperties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author gx
 * @date 2017/4/7
 *
 */
@SuppressWarnings("SpringJavaAutowiringInspection")
@Configuration
@ConditionalOnBase
@EnableConfigurationProperties(DruidDataSourceProperties.class)
public class DataSourceConfig {
    protected final Log logger = LogFactory.getLog(this.getClass());

    @Autowired
    DruidDataSourceProperties druidDataSourceProperties;
    @Bean(name = "readDataSource")
    @Qualifier("readDataSource")
    @ConfigurationProperties(prefix="spring.datasource.read")
    public DataSource readDataSource() {
        logger.info("-------------------- readDataSource init ---------------------");
        DataSource dataSource = DataSourceBuilder.create().type(DruidDataSource.class).build();
        druidDataSourceProperties.buildDataSource(dataSource);
        return dataSource;
    }

    @Bean(name = "writeDataSource")
    @Qualifier("writeDataSource")
    @Primary
    @ConfigurationProperties(prefix="spring.datasource.write")
    public DataSource writeDataSource() {
        logger.info("-------------------- writeDataSource init ---------------------");
        DataSource dataSource = DataSourceBuilder.create().type(DruidDataSource.class).build();
        druidDataSourceProperties.buildDataSource(dataSource);
        return dataSource;
    }
    @Bean
    public DataSource dataSource(){
        ChooseDataSource chooseDataSource = new ChooseDataSource();
        Map<Object,Object> map = new HashMap<>(16);
        map.put("write",readDataSource());
        map.put("read",writeDataSource());
        chooseDataSource.setTargetDataSources(map);
        Map<String,String> methodTypeMap = Maps.newHashMap();
        methodTypeMap.put("read",",get,select,count,list,query,");
        methodTypeMap.put("write",",add,insert,create,update,delete,remove,");
        chooseDataSource.setMethodType(methodTypeMap);
        chooseDataSource.setDefaultTargetDataSource(writeDataSource());
        return  chooseDataSource;
    }
}
